<template>
  <div class="attendance-types-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增考勤类型
      </el-button>
      <el-upload
        class="excel-upload"
        action="#"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleExcelChange"
      >
        <el-button type="success">
          <el-icon><Upload /></el-icon>导入Excel
        </el-button>
      </el-upload>
    </div>

    <!-- 考勤类型列表 -->
    <el-table
      v-loading="loading"
      :data="attendanceTypes"
      style="width: 100%"
      border
    >
      <el-table-column prop="type_id" label="类型ID" width="120" />
      <el-table-column prop="type_name" label="类型名称" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增考勤类型' : '编辑考勤类型'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="类型ID" prop="type_id">
          <el-input v-model="form.type_id" placeholder="请输入类型ID" />
        </el-form-item>
        <el-form-item label="类型名称" prop="type_name">
          <el-input v-model="form.type_name" placeholder="请输入类型名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAttendanceTypeStore } from '@/stores/attendanceType'
import { useExcelImport } from '@/hooks/useExcelImport'
import type { FormInstance } from 'element-plus'
import { storeToRefs } from 'pinia'

// 状态管理
const attendanceTypeStore = useAttendanceTypeStore()
const { attendanceTypes, loading } = storeToRefs(attendanceTypeStore)

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const form = ref({
  type_id: 0,
  type_name: ''
})

// 表单验证规则
const rules = {
  type_id: [
    { required: true, message: '请输入类型ID', trigger: 'blur' },
    { pattern: /^\d+$/, message: '类型ID必须为数字', trigger: 'blur' }
  ],
  type_name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' }
  ]
}

// Excel导入
const { readExcelFile, validateImportData } = useExcelImport()

// 获取考勤类型列表
const fetchAttendanceTypes = async () => {
  await attendanceTypeStore.fetchAttendanceTypes()
}

// 新增考勤类型
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    type_id: 0,
    type_name: ''
  }
  dialogVisible.value = true
}

// 编辑考勤类型
const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result;
        if (dialogType.value === 'add') {
          result = await attendanceTypeStore.createAttendanceType(form.value)
        } else {
          result = await attendanceTypeStore.updateAttendanceType(
            form.value.type_id,
            form.value
          )
        }
        
        if (result) {
          dialogVisible.value = false
          ElMessage.success(
            dialogType.value === 'add' ? '新增成功' : '更新成功'
          )
          // 刷新数据
          await fetchAttendanceTypes()
        }
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 处理Excel文件上传
const handleExcelChange = async (file: any) => {
  try {
    // 指定字段映射
    const headerMap = {
      '类型序号':'type_id',
      '类型名称':'type_name'
    }
    const data = await readExcelFile(file.raw, headerMap, '考勤类型表')

    console.log(data)
    
    // 验证数据
    const requiredFields = ['type_id', 'type_name']
    if (!validateImportData(data, requiredFields)) {
      return
    }
    
    // 转换数据格式
    const typesToCreate = data.map(item => ({
      type_id: Number(item.type_id),
      type_name: item.type_name
    }))
    
    // 批量创建考勤类型
    const result = await attendanceTypeStore.batchCreateAttendanceTypes(typesToCreate)
    
    if (result) {
      ElMessage.success('导入成功')
      // 刷新数据
      await fetchAttendanceTypes()
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchAttendanceTypes()
})
</script>

<style scoped>
.attendance-types-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.excel-upload {
  display: inline-block;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 添加表格容器样式 */
:deep(.el-table) {
  flex: 1;
  overflow: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

:deep(.el-table__inner-wrapper) {
  height: 100%;
}

:deep(.el-table__body) {
  height: 100%;
}
</style> 